import { useRouter } from 'next/router'
import useSWR from 'swr'
import type { Person, ResponseError } from '../api/people'
import { Response } from '@/types/type'
import type { InferGetServerSidePropsType, InferGetStaticPropsType } from 'next'
import { SWRConfig } from 'swr/_internal'
import { request } from '@/api'

export default function PersonPage({
  fallback
}: InferGetStaticPropsType<typeof getStaticProps>) {
  return (
    <SWRConfig value={{ fallback }}>
      <Article />
    </SWRConfig>
  )
}

function Article() {
  const { data, error, isLoading, isValidating } = useSWR('/api/people')
  if (error) return <div>{error.message}</div>
  if (isLoading) return <div>Loading...</div>

  if (!data) return null
  return (
    <table>
      <thead>
        <tr>
          <th>Name</th>
          <th>Height</th>
          <th>Mass</th>
          <th>Hair color</th>
          <th>Skin color</th>
          <th>Eye color</th>
          <th>Gender</th>
        </tr>
      </thead>
      <tbody>
        {data.map((person: Person) => (
          <tr key={person.id}>
            {isValidating ? (
              <td colSpan={7} align='center'>
                Validating...
              </td>
            ) : (
              <>
                <td>{person.name}</td>
                <td>{person.height}</td>
                <td>{person.mass}</td>
                <td>{person.hair_color}</td>
                <td>{person.skin_color}</td>
                <td>{person.eye_color}</td>
                <td>{person.gender}</td>
              </>
            )}
          </tr>
        ))}
      </tbody>
    </table>
  )
}

/**
 * （静态生成）：在构建时获取数据。
 */
export async function getStaticProps() {
  const [_, r] = await request({
    url: '/api/people'
  })

  return {
    props: {
      fallback: {
        '/api/people': r
      }
    }
  }
}
